<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/25/24
 * Time: 2:12 PM
 */

namespace App\Services;

use App\Models\WechatDepartment;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

class DepartmentService
{

    /**
     * 获取部门列表
     *
     * @param $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getDepList($params)
    {
        $corpId = $params['corp_id'] ?? '';

        $list = WechatDepartment::query()->where('corp_id', $corpId)->get()->toArray();

        return $this->buildDepartmentTree($list);
    }


    /**
     * 构建树形部门
     *
     * @param $departments
     * @param int $parentId
     * @return array
     */
    private function buildDepartmentTree($departments, $parentId = 0)
    {
        $tree = [];

        foreach ($departments as $department) {
            if ($department['parent_id'] == $parentId) {
                $children = $this->buildDepartmentTree($departments, $department['department_id']);
                if ($children) {
                    $department['children'] = $children;
                }
                $tree[] = $department;
            }
        }

        return $tree;
    }


    /**
     * 创建部门
     *
     * @param $params
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function createDepartment($params)
    {
        $corpId   = $params['corp_id'] ?? '';
        $name     = $params['name'] ?? '';
        $parentId = $params['parent_id'] ?? 0;

        $client   = new Client();
        $service  = new KfAccountService();
        $token    = $service->getReplaceAccessToken($corpId);
        $body     = [
            'headers'            => $service->headers,
            RequestOptions::JSON => [
                'name'     => $name,
                'parentid' => $parentId,
            ]
        ];
        $response = $client->request('POST', sprintf($service->api['create_dep'], $token), $body);
        if ($response->getStatusCode() != 200) {

            return false;
        }
        $contents = $response->getBody()->getContents();
        $data     = json_decode($contents, true);
        if ($data['errcode'] != 0) {

            return false;
        }

        if ($depId = $data['id'] ?? 0) {
            $dep                  = new WechatDepartment();
            $dep->corp_id         = $corpId;
            $dep->department_id   = $depId;
            $dep->department_name = $name;
            $dep->parent_id       = $parentId;
            $dep->save();
        }

        return true;
    }


    /**
     * 删除部门
     *
     * @param $params
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function delDepartment($params)
    {
        $corpId = $params['corp_id'] ?? '';
        $id     = $params['id'] ?? 0;

        $client   = new Client();
        $service  = new KfAccountService();
        $token    = $service->getReplaceAccessToken($corpId);
        $response = $client->request('GET', sprintf($service->api['del_dep'], $token, $id));
        if ($response->getStatusCode() != 200) {

            return false;
        }
        $contents = $response->getBody()->getContents();
        $data     = json_decode($contents, true);

        if ($data['errcode'] == 0) {
            $dep = WechatDepartment::query()->where('corp_id', $corpId)->where('department_id', $id)->first();
            if ($dep) {
                $dep->delete();
            }

            return true;
        }

        return false;
    }
}
